package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import com.atguigu.gulimall.member.vo.MemberRegistVo;
import com.atguigu.gulimall.member.vo.MemeberLoginVo;
import com.atguigu.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Resource
    MemberLevelDao memberLevelDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegistVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        //检查用户名和手机号是否是唯一  为了让controller感知异常,异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());
        //设置默认等级
        MemberLevelEntity entity = memberLevelDao.getDefautLevel();
        memberEntity.setNickname(vo.getUsername());
        memberEntity.setLevelId(entity.getId());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUsername());
        //密码加密处理
        /**
         * MD5不能直接进行密码加密可以用彩虹表进行得出
         * 
         */
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        //其他默认信息
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer mobile = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(mobile>0){
            throw new PhoneExistException();

        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){
            throw new UsernameExistException();
        }

    }

    @Override
    public MemberEntity login(MemeberLoginVo vo) {
        String loginacct = vo.getLoginacct();

        //去数据库查询
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if(memberEntity==null){
            return null;
        }else{
            String passwordDB = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(vo.getPassword(), passwordDB);
            if(matches){
                return memberEntity;
            }else{
                return null;
            }

        }
    }

    @Override
    public MemberEntity login(SocialUser vo) throws Exception {
        //登录和注册合并逻辑
        String uid = vo.getUid();
        //判断当前社交用户是否已经登录过系统
        MemberEntity member = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        //登录注册
        if(member != null){
            MemberEntity update = new MemberEntity();
            update.setId(member.getId());
            update.setAccessToken(vo.getAccess_token());
            update.setExpiredIn(vo.getExpires_in());
            this.baseMapper.updateById(update);
            member.setAccessToken(vo.getAccess_token());
            member.setExpiredIn(vo.getExpires_in());
            return member;
        }else{
            //没有查到社交信息就要注册
            MemberEntity regist = new MemberEntity();
            try {
                //查出当前社交账号信息
                Map<String,String> query = new HashMap<String,String>();
                query.put("access_token", vo.getAccess_token());
                query.put("uid",vo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api/weibo.com",
                        "/2/users/show.json", "get",
                        new HashMap<String, String>(), query);
                if(response.getStatusLine().getStatusCode()==200){
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender("m".equals(gender)?1:0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            regist.setSocialUid(vo.getUid());
            regist.setAccessToken(vo.getAccess_token());
            regist.setExpiredIn(vo.getExpires_in());
            this.baseMapper.insert(regist);
            return regist;

        }
    }

}